package com.sq.partner.manager.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.mybatis.model.GatewayAgency;
import com.sq.partner.manager.mybatis.model.GatewayAgencyChannel;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TreeDto;
import com.sq.partner.manager.service.IGatewayAgencyInfoConfigService;
import com.sq.partner.manager.service.IGatewayChannelInfoConfigService;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;

/**
 * 
 * @author guozizhou 中介机构配置
 */
@Controller
@RequestMapping(value = "/agencyManage")
public class AgencyInfoConfigController {
	private static Logger logger = LogUtil.getLog(AgencyInfoConfigController.class);
	@Resource
	private IGatewayAgencyInfoConfigService agencyInfoConfigService;
	@Resource
	private IGatewayChannelInfoConfigService channelInfoConfigService;
	
	@RequestMapping(value = "/agencyInfoConfig")
	public String agencyInfoConfig(ModelMap model) throws Exception {
		return "appManage/agencyInfoConfig";
	}

	@RequestMapping(value = "/queryByCriteria", method = RequestMethod.POST)
	@ResponseBody
	public Page<GatewayAgency> queryInfoByCriteria(HttpSession session,GatewayAgency agency,Integer pageIndex) throws Exception {
		Page<GatewayAgency> page = new Page<GatewayAgency>();
		page.setCurrent(pageIndex);
		page.setType(agency);
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		logger.debug("---come into agency successful param "+agency.getAgencyCode()+"------");
		return agencyInfoConfigService.queryInfoByCriteria(page,user);
	}
	
	@RequestMapping(value = "/saveAgencyInfo", method = RequestMethod.POST)
	@ResponseBody
	public Result saveAgencyInfo(HttpSession session,String agencyCode,String agencyName,String deptCode,String flag, String preDeptCode) throws Exception {
		if(!(channelInfoConfigService.checkIsHasPrivilege(session, deptCode))){
			return Result.error("权限不足，无权操作该分公司!");
		}else if(StrUtil.isEmpty(flag)){
			return Result.error("系统正忙，请稍后重试");
		}else if(StrUtil.isEmpty(agencyCode)){
			return Result.error("请输入中介公司代码");
		}else if(StrUtil.isEmpty(agencyName)){
			return Result.error("请输入中介公司名称");
		}else if(StrUtil.isEmpty(deptCode)){
			return Result.error("请选择所属分公司");
		}
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		GatewayAgency agency = new GatewayAgency();
		agency.setAgencyCode(agencyCode);
		agency.setAgencyName(agencyName);
		agency.setDeptCode(deptCode);
 		agency.setOperUser(user.getUserid());
		agency.setOperTime(new Date());
		if("save".equals(flag)){
			if(agencyInfoConfigService.addAgencyInfo(agency)){
				return Result.success("添加成功！");
			}
			return Result.error("添加失败！");
		}else if("update".equals(flag)){
			agencyInfoConfigService.updateAgencyInfo(agency);
			return Result.success("更新成功！");
		}else{
			return Result.error("操作失败，系统检查出非法数据传入，请修改！");
		}
	}
	
	@RequestMapping(value = "/deleteAgencyInfoByCode", method = RequestMethod.POST)
	@ResponseBody
	public Result delAgencyInfo(HttpSession session,String agencyCode,String deptCode) throws Exception {
		if(StrUtil.isEmpty(deptCode)){
			return Result.error("操作失败，系统检查出非法数据传入，请修改！");
		}else if(!(channelInfoConfigService.checkIsHasPrivilege(session, deptCode))){
			return Result.error("权限不足，无权操作该分公司!");
		}else if(StrUtil.isEmpty(agencyCode)){
			return Result.error("中介公司代码不能为空");
		}else if(agencyInfoConfigService.checkIsExistFacadeUser(agencyCode)>0){
			return Result.error("已有出单用户配置该中介公司，不能删除!");
		}
		GatewayAgency agency = new GatewayAgency();
		agency.setAgencyCode(agencyCode);
		GatewayAgencyChannel gac = new GatewayAgencyChannel();
		gac.setAgencyCode(agencyCode);
		//删除中间关系表
		agencyInfoConfigService.delPrivilegesByAgencyCode(gac);
		//删除中介公司表
		boolean agencyR = agencyInfoConfigService.deleteAgencyInfo(agency);
		if(agencyR)
		{
			return Result.success("删除成功！");
		}
		return Result.error("删除失败！");
	}
	
	@RequestMapping(value = "/queryAgencyInfoByAgencyCode", method = RequestMethod.POST)
	@ResponseBody
	public Page<GatewayAgency> queryAgencyInfoByAgencyCode(String agencyCode) throws Exception {
		Page<GatewayAgency>  page = new Page<GatewayAgency>();
		if(StrUtil.isEmpty(agencyCode)){
			page.setResult("error");
			page.setMessage("中介公司代码不能为空");
			return page;
		}
		GatewayAgency agency = new GatewayAgency();
		agency.setAgencyCode(agencyCode);
		page.setType(agencyInfoConfigService.queryAgencyInfoByCode(agency));
		return page;
	}
	
	@RequestMapping(value = "/getChannelInfoListTree", method = RequestMethod.POST)
	public @ResponseBody Page<TreeDto> queryChannelInfoListTree(HttpSession session,String deptCode) throws Exception{
		Page<TreeDto> page = new Page<TreeDto>();
		if(StrUtil.isEmpty(deptCode)){
			page.setResult("error");
			page.setMessage("操作失败，系统检查出非法数据传入，请修改！");
			return page;
		}else if(!(channelInfoConfigService.checkIsHasPrivilege(session, deptCode))){
			page.setResult("error");
			page.setMessage("权限不足，无权操作该分公司!");
			return page;
		}
		List<TreeDto> list = agencyInfoConfigService.queryChannelInfoListsForTree(deptCode);
		page.setData(list);
		return page;
	}
	
	@RequestMapping(value = "/getChannelInfosOfCurrAgency", method = RequestMethod.POST)
	public @ResponseBody List<GatewayAgencyChannel> queryBranchDepts(String agencyCode) throws Exception{
		if(StrUtil.isEmpty(agencyCode)){
			return null;
		}
		GatewayAgencyChannel gac = new GatewayAgencyChannel();
		gac.setAgencyCode(agencyCode);
		List<GatewayAgencyChannel> list = agencyInfoConfigService.queryPrivilegesByAgencyCode(gac);
		return list;
	}
	
	@RequestMapping(value = "/bindChannelInfoListsToAgencyChannel", method = RequestMethod.POST)
	public @ResponseBody Result bindChannelInfoListsToAgencyChannel(HttpSession session, String agencyCode,String deptIdStr, String deptCodeStr) throws Exception{
		if(StrUtil.isEmpty(agencyCode)){
			return Result.error("中介公司代码不能为空！");
		}else if(StrUtil.isEmpty(deptIdStr)){
			return Result.error("请至少配置一个合作伙伴！");
		} else if(StrUtil.isEmpty(deptCodeStr)){
			return Result.error("选择配置的合作伙伴所属分公司代码不能为空！");
		}
		//验证分公司权限
		if(!(channelInfoConfigService.checkIsHasPrivilege(session, deptCodeStr))){
			return Result.error("权限不足，无权操作该分公司!");
			
		}
		GatewayUser user = (GatewayUser)session.getAttribute(Constants.SESSION_USER);
		//每次配置机构之前，删除该中介机构所有的权限配置
		GatewayAgencyChannel delgac = new GatewayAgencyChannel();
		delgac.setAgencyCode(agencyCode);
		agencyInfoConfigService.delPrivilegesByAgencyCode(delgac);
		//再次插入数据
		String acArr[] = deptIdStr.split(",");
		for(int i=0;i<acArr.length;i++){
			GatewayAgencyChannel gac = new GatewayAgencyChannel(); 
			gac.setAgencyCode(agencyCode);
			gac.setChannelCode(acArr[i]);
			gac.setOperTime(new Date());
			gac.setOperUser(user.getUserid());
			agencyInfoConfigService.addPrivilegesToOneAgency(gac);
		}
		return Result.success("中介公司配置权限成功");
	}
}
